#!/usr/bin/env bash
function pauseErr(){
   if [ $? -ne 0 ];then
       echo "pause because of failed ; Ctrl + C to exit"
       sleep 1000
       exit
   fi
}

upload_dir="upload_bang"
download_dir="proguard"
bangcle_ftp="phoenix_bangcle"
echo "bang bang security firm $1 ....."
api_key="dc68cc60-0dbd-4f45-94b1-2f3d16d73757"
api_sec="d7d314ce-942c-4f10-a5c1-10b5100f8357"
username="szlbkj"
policy_id="1"
host="192.168.8.100:8000"

if [ "x$1" != "x" ];then
    [ "$1" == "sdk" ] && firm_type=1
    [ "$1" == "so" ] && firm_type=2
    if [ "$1" != "so"  -a "$1" != "sdk" ];then
        echo please input sdk or so
        pauseErr
    fi
else
    echo please input your need, sdk or so
    pauseErr
fi

if [ -d $upload_dir ]; then
    echo delete old upload_so and create a new one
    rm -rf $upload_dir
fi

if [ -d $download_dir ]; then
    echo delete old download_so and create a new one
    rm -rf $download_dir
fi

mkdir $upload_dir
mkdir $download_dir

if [ "$1" == "sdk" ];then
    cp ../android/sink/target/*.aar $upload_dir
fi

if [ "$1" == "so" ];then
    zip -r libs.zip libs
    mv libs.zip $upload_dir/
fi

zip_flag=`ls $upload_dir`
if [ "x$zip_flag" == "x" ];then
    echo have no so zip $zip_flag and exit
    sleep 100
    exit 1
else
    echo origin file size:
    du -sh $upload_dir/*
    echo "start upload firm $zip_flag ...."
fi

java -jar "sec_api.jar" -i $host -u $username -a $api_key -c $api_sec  -p "$upload_dir" -t $policy_id -f $firm_type
pauseErr
echo ==============================upload $1 finished=======================

echo sleep 30 to wait download .....
sleep 30
echo "start download firmed so...."
# 等待30S之后开始下载（大部分情况下30秒等待时间已经足够）
# 下载失败5秒一个重试请求，最大等待时长为 30 + 20*5 = 130S
for((i=0;i<20;i++))
do
{
    java -jar "sec_api.jar" -i $host -u $username -a $api_key -c $api_sec -d "$download_dir" -f $firm_type 
    pauseErr
    echo ==============================download $1 finished=======================

    echo "local check downlaod result .... "
    download_flag=`ls $download_dir`
    echo download_flag=$download_flag
    if [ "x$download_flag" == "x" ] ;then
        echo download firmed so failed and sleep 5s and $i retry...
        sleep 5 
    else
        echo download firmed so success
        break
    fi
}
done

if [ "x$download_flag" == "x" ] ;then
    echo download firmed so failed...
    sleep 100
    exit 1
else
    echo download firmed so success
    echo firmed size:
    du -sh $download_dir/*
    if [ "$1" == "so" ];then
        unzip $download_dir/*.zip -d $download_dir
        rm -rf $download_dir/*.zip
        pauseErr
    fi
fi

